package org.example.project3.Service;

import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import lombok.extern.slf4j.Slf4j;
import org.example.project3.DTO.ArticleDTO;
import org.example.project3.DTO.PageQueryDTO;
import org.example.project3.Entity.Acontents;
import org.example.project3.Entity.Article;
import org.example.project3.Mapper.AcontentsMapper;
import org.example.project3.Mapper.ArticleMapper;
import org.example.project3.VO.ArticleVO;
import org.example.project3.VO.PageVO;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDateTime;
import java.util.List;
@Slf4j
@Service
public class ArticleServiceImpl implements ArticleService{
    @Autowired
    private ArticleMapper articleMapper;
    @Autowired
    private AcontentsMapper acontentsMapper;
    public PageVO search(PageQueryDTO dto){
        PageHelper.startPage(dto.getPage(),dto.getPageSize());
        List<Article> articleList = articleMapper.search(dto);
        PageInfo<Article> pageInfo = new PageInfo<>(articleList);
        Long totals = pageInfo.getTotal();
        log.info("totals:{}",totals);
        return PageVO.builder()
                .totals(totals)
                .list(articleList)
                .build();
    }

    public void add(ArticleDTO dto){
        //完善信息，插入article表
        Article article = new Article();
        BeanUtils.copyProperties(dto,article);
        article.setCreateTime(LocalDateTime.now());
        article.setUpdateTime(LocalDateTime.now());
        articleMapper.add(article);
        //插入content表
        Acontents acontents = new Acontents();
        acontents.setArticleId(article.getId());
        acontents.setContents(dto.getContent());
        acontentsMapper.insert(acontents);
    }
    @Transactional
    public void delete(Integer id){
        //删除主表
        articleMapper.delete(id);
        //删除content表
        acontentsMapper.delete(id);
    }

    public ArticleVO getByid(Integer id){
        Article article = articleMapper.getByid(id);
        String contents = acontentsMapper.getByid(id);
        ArticleVO vo = new ArticleVO();
        BeanUtils.copyProperties(article,vo);
        vo.setContent(contents);
        return vo;
    }

    @Transactional
    public void edit(ArticleDTO dto){
        //修改article表
        Article article = new Article();
        BeanUtils.copyProperties(dto,article);
        article.setUpdateTime(LocalDateTime.now());
        articleMapper.update(article);
        //修改content表
        Acontents acontents = new Acontents();
        acontents.setArticleId(dto.getId());
        acontents.setContents(dto.getContent());
        acontentsMapper.edit(acontents);
    }
}
